package com.teaching.management.controller.api;

import com.teaching.management.entity.Teacher;
import com.teaching.management.entity.User;
import com.teaching.management.repository.TeacherRepository;
import com.teaching.management.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 教师管理相关的REST API
 */
@RestController
@RequestMapping("/api/admin/teachers")
public class AdminTeacherRestController {

    @Autowired
    private TeacherRepository teacherRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 获取所有教师
     */
    @GetMapping
    public ResponseEntity<?> getAllTeachers(HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        List<Teacher> teachers = teacherRepository.findAll();
        return ResponseEntity.ok(teachers);
    }

    /**
     * 根据条件搜索教师
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchTeachers(@RequestParam("term") String searchTerm, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 创建模糊匹配，匹配教师工号或姓名
        Teacher example = new Teacher();
        example.setTeacherId(searchTerm);
        example.setName(searchTerm);

        ExampleMatcher matcher = ExampleMatcher.matchingAny()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase();

        List<Teacher> teachers = teacherRepository.findAll(Example.of(example, matcher));
        return ResponseEntity.ok(teachers);
    }

    /**
     * 获取单个教师详情
     */
    @GetMapping("/{teacherId}")
    public ResponseEntity<?> getTeacher(@PathVariable String teacherId, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        Optional<Teacher> teacherOpt = teacherRepository.findById(teacherId);
        if (teacherOpt.isPresent()) {
            return ResponseEntity.ok(teacherOpt.get());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("教师不存在");
        }
    }

    /**
     * 添加新教师
     */
    @PostMapping
    @Transactional
    public ResponseEntity<?> addTeacher(@RequestBody Map<String, Object> teacherData, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 从请求中提取教师信息和用户信息
        String teacherId = (String) teacherData.get("teacherId");
        String name = (String) teacherData.get("name");
        String gender = (String) teacherData.get("gender");
        String department = (String) teacherData.get("department");
        String title = (String) teacherData.get("title");
        String birthDate = (String) teacherData.get("birthDate");
        String hireDate = (String) teacherData.get("hireDate");
        String username = (String) teacherData.get("username");
        String password = (String) teacherData.get("password");

        // 检查教师ID是否已存在
        if (teacherRepository.existsById(teacherId)) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("教师工号已存在");
        }

        // 检查用户名是否已存在
        if (userRepository.findByUsernameAndPasswordAndRole(username, null, null) != null) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("用户名已存在");
        }

        // 创建用户
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setRole("教师");
        User savedUser = userRepository.save(newUser);

        // 创建教师
        Teacher teacher = new Teacher();
        teacher.setTeacherId(teacherId);
        teacher.setUserId(savedUser.getUserId());
        teacher.setName(name);
        teacher.setGender(gender);
        teacher.setDepartment(department);
        teacher.setTitle(title);
        teacher.setBirthDate(java.sql.Date.valueOf(birthDate));
        teacher.setHireDate(java.sql.Date.valueOf(hireDate));

        Teacher savedTeacher = teacherRepository.save(teacher);
        return ResponseEntity.status(HttpStatus.CREATED).body(savedTeacher);
    }

    /**
     * 更新教师信息
     */
    @PutMapping("/{teacherId}")
    public ResponseEntity<?> updateTeacher(
            @PathVariable String teacherId,
            @RequestBody Teacher teacher,
            HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 确保路径中的ID与请求体中的ID一致
        if (!teacherId.equals(teacher.getTeacherId())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("教师工号不一致");
        }

        // 检查教师是否存在
        if (!teacherRepository.existsById(teacherId)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("教师不存在");
        }

        Teacher updatedTeacher = teacherRepository.save(teacher);
        return ResponseEntity.ok(updatedTeacher);
    }

    /**
     * 删除教师
     */
    @DeleteMapping("/{teacherId}")
    @Transactional
    public ResponseEntity<?> deleteTeacher(@PathVariable String teacherId, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 检查教师是否存在
        Optional<Teacher> teacherOpt = teacherRepository.findById(teacherId);
        if (!teacherOpt.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("教师不存在");
        }

        try {
            // 获取关联的用户ID
            Integer userId = teacherOpt.get().getUserId();

            // 删除教师
            teacherRepository.deleteById(teacherId);

            // 删除关联的用户
            userRepository.deleteById(userId);

            return ResponseEntity.ok().build();
        } catch (Exception e) {
            // 可能因为外键约束而无法删除
            return ResponseEntity.status(HttpStatus.CONFLICT)
                    .body("删除失败，该教师已被课程引用，请先解除关联");
        }
    }
}